package com.bzy.blp.controller;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.stream.StreamResult;

import com.alibaba.fastjson.JSON;
import com.bzy.common.util.CommonsUtils;
import com.bzy.common.util.DateUtils;
import com.bzy.common.util.LoggerUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;

@Api(value = "upload",description = "文件上传")
@RestController
@RequestMapping("/upload")
public class UploadFileController {
	
	private final static String blp_FILE_UPLOAD = "bpl_file_image";
	

	/**
	 * 
	 */
	@ApiOperation(value = "附件上传（图片）,支持批量", notes = "", response = String.class)
	@RequestMapping(value = "/uploadImageMulit", method = { POST })
	@ResponseBody
	public String uploadBappImageMulit(@ApiParam(name="随便填写", value="文件（图片上传）", required = true)MultipartFile file1
			,HttpServletRequest request, HttpServletResponse response) throws Exception {

		String str = "";
		String folder = request.getParameter("folder");
		if (StringUtils.isBlank(folder)) {
			folder = "/temp"; // 临时文件夹名称
		}

		List<Map<String, Object>> fileList = fileTransferTodisk_cms(request, folder);

		str = "{\"success\":\"true\",\"message\":\"上传成功\",\"avatar\":\"";

		int index = 0;
		for (Map<String, Object> map : fileList) {
			if (index > 0) {
				str += ",";
			}
			str += "/" + map.get("avatar");
			index ++ ;
		}
		
		LoggerUtil.info("index ...... "+index);
		str += "\",\"website\":\"" + fileList.get(0).get("website") + ",";

		str = str.substring(0, str.length() - 1);

		str += "\"}";

		return str;
	}
	
	
	
	private List<Map<String, Object>> fileTransferTodisk_cms(HttpServletRequest request, String folder) throws Exception {
		List<Map<String, Object>> list = new ArrayList<>();

		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {

			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

			// 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();

			// 记录上传过程起始时的时间，用来计算上传时间
			long pre = System.currentTimeMillis();
			LoggerUtil.info(".... start upload pre ...." + pre);

			while (iter.hasNext()) {

				Map<String, Object> map = new HashMap<>();
				// 取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());

				if (file != null && !file.getOriginalFilename().equals("")) {

					// 获取图片大小
					Long picSize = (file.getSize() / 1024);

					String date = DateUtils.toDateString(new Date(), DateUtils.ISO_DATE_FORMATTER);
					String filename = folder + "/" + date + "/";// 生成头像图片路径

					String contextPath = request.getContextPath();

					String cip = request.getRequestURL().substring(0,
							request.getRequestURL().lastIndexOf(contextPath) + 1);


					String strURL = getClassPath_bapp();
					String path = strURL.substring(0, strURL.lastIndexOf(contextPath) + 1)
							+ blp_FILE_UPLOAD + "/" + filename;
					System.out.println(" ###### path : " + path);

					File fileP = new File(path);
					if (!fileP.exists()) {
						fileP.mkdirs();
					}

					String fileName = file.getOriginalFilename();

					String fileType = fileName.substring(fileName.lastIndexOf(".")); // 文件后缀名

					String aliseName = CommonsUtils.getNoLineUId() + fileType;


					String realPath = path + aliseName;
					System.out.println(path + aliseName);
					realPath = "";
					File uploadFile = new File(path + aliseName);
					System.out.println(uploadFile.getPath());
					file.transferTo(uploadFile);

					// 止
					StringBuffer url = new StringBuffer();

					url.append(filename);
					url.append(aliseName);
					map.put("avatar", url.toString());// 用户id

					String physicalPath = path + aliseName;

//					if (picSize > 600) {
//						ImageUtil.scaleImageWithParams(physicalPath, physicalPath, 1080, 1000, true,
//								fileType.replace(".", ""));
//					}

					map.put("avatar", blp_FILE_UPLOAD + url.toString());
					map.put("website", cip);
					map.put("imageurl", blp_FILE_UPLOAD + url.toString());
					map.put("filetype", fileType);
					map.put("picsize", picSize);
					map.put("filename", fileName);
					list.add(map);

				}
			}

			long after = System.currentTimeMillis();
			LoggerUtil.info(".... end upload commit ...." + after);
		}
		return list;
	}
	
	
	/**
	 * 获取当前类的物理路径
	 * 
	 * @return
	 */
	public String getClassPath_bapp() {
		String strClassName = getClass().getName();
		String strPackageName = "";
		if (getClass().getPackage() != null) {
			strPackageName = getClass().getPackage().getName();
		}
		String strClassFileName = "";
		if (!"".equals(strPackageName)) {
			strClassFileName = strClassName.substring(strPackageName.length() + 1, strClassName.length());
		} else {
			strClassFileName = strClassName;
		}
		URL urlR = null;
		urlR = getClass().getResource(strClassFileName + ".class");
		String strURL = urlR.toString();
		strURL = strURL.substring(strURL.indexOf('/') + 1, strURL.lastIndexOf('/'));
		return strURL;
	}
	
	
	/**
	 * ueditor文本编辑器上传图片
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/uploadImageUeditorMulit", method = { GET, POST })
	@ResponseBody
	public String uploadImageUeditorMulit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<>();

		String rootPath = request.getSession().getServletContext().getRealPath("/");
		System.out.println("rootPath......." + rootPath);

		String folder = request.getParameter("folder");
		if (StringUtils.isBlank(folder)) {
			folder = "temp"; // 临时文件夹名称
		}

		List<Map<String, Object>> fileList = fileTransferTodisk_cms(request, folder);

		// 单张上传返回
		map.put("state", "SUCCESS");
		map.put("original", fileList.get(0).get("filename"));
		map.put("size", fileList.get(0).get("picsize"));
		map.put("title", fileList.get(0).get("filename"));
		map.put("type", fileList.get(0).get("filetype").toString());
		map.put("title", fileList.get(0).get("imageurl").toString());
		String imageurl = fileList.get(0).get("imageurl").toString();
		map.put("url", imageurl);

		return JSON.toJSONString(map);

	}
}
